<template>
  <div class="user-management">
    <el-card class="card-container">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold text-gray-800 flex items-center">
            <el-icon class="mr-2 text-primary"><User /></el-icon>
            用户管理
          </h2>
          <el-button 
            type="primary" 
            @click="openUserDialog()"
            class="flex items-center transition-all duration-300 hover:shadow-lg">
            <el-icon><Plus /></el-icon>
            <span>新增用户</span>
          </el-button>
        </div>
      </template>

      <el-table 
        :data="userList" 
        border 
        stripe
        highlight-current-row
        class="rounded-lg overflow-hidden mb-4 transition-all duration-300 hover:shadow-md">
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.gender === 0 ? 'primary' : 'success'">
              {{ scope.row.gender === 0 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openUserDialog(scope.row)"
              class="transition-all duration-300 hover:scale-105">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteUser(scope.row)"
              class="transition-all duration-300 hover:scale-105">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex flex-col md:flex-row justify-between items-center mt-4 gap-4">
        <div class="text-sm text-gray-500">
          共 {{ total }} 条记录
        </div>
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          class="pagination w-full md:w-auto"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="50%">
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="手机号码">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="密码" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { Plus, Edit, Delete, User } from '@element-plus/icons-vue'
import { listUser, getUser, addUser, updateUser, delUser } from '@/api/user'

// 引用表单进行验证
const formRef = ref(null)

// 用户列表
const userList = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 用户表单
const userForm = reactive({
  id: null,
  userName: '',
  phone: '',
  email: '',
  gender: 0,
  password: ''
})

// 获取用户列表
const getUserList = async (params = {}) => {
  try {
    const res = await listUser({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...params
    })
    userList.value = res.data || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 打开用户对话框
const openUserDialog = (user) => {
  if (user) {
    // 编辑模式
    isEdit.value = true
    Object.assign(userForm, user)
  } else {
    // 新增模式
    isEdit.value = false
    // 重置表单
    Object.assign(userForm, {
      id: null,
      userName: '',
      phone: '',
      email: '',
      gender: 0,
      password: ''
    })
  }

  dialogVisible.value = true
  
  // 重置表单验证状态
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 验证并保存用户
const validateAndSave = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      saveUser()
    } else {
      return false
    }
  })
}

// 保存用户
const saveUser = async () => {
  try {
    if (isEdit.value) {
      // 编辑用户
      await updateUser(userForm)
      ElMessage.success('用户更新成功')
    } else {
      // 新增用户
      await addUser(userForm)
      ElMessage.success('用户添加成功')
    }

    // 关闭对话框
    dialogVisible.value = false

    // 刷新用户列表
    getUserList()
  } catch (error) {
    console.error('保存用户失败', error)
    ElMessage.error(error.message || '保存用户失败')
  }
}

// 删除用户
const deleteUser = (user) => {
  ElMessageBox.confirm(`确定要删除用户 ${user.userName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        await delUser(user.id)
        ElMessage.success('用户删除成功')
        getUserList()
      } catch (error) {
        console.error('删除用户失败', error)
        ElMessage.error(error.message || '删除用户失败')
      }
    })
    .catch(() => {})
}

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  getUserList()
}

// 每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getUserList()
}

// 对话框关闭前处理
const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭对话框吗？未保存的修改将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      done()
    })
    .catch(() => {})
}

// 初始化
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary: #409eff;
  --success: #67c23a;
  --warning: #e6a23c;
  --danger: #f56c6c;
  --info: #909399;
  --bg-light: #f5f7fa;
  --bg-lighter: #fafafa;
  --text-primary: #303133;
  --text-secondary: #606266;
  --text-placeholder: #909399;
  --border-color: #dcdfe6;
  --border-radius: 8px;
  --border-radius-lg: 12px;
  --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  --box-shadow-hover: 0 6px 16px rgba(0, 0, 0, 0.12);
}

/* 卡片容器 */
.card-container {
  border-radius: var(--border-radius-lg);
  box-shadow: var(--box-shadow);
  transition: all 0.3s ease;
  background-color: white;
}

.card-container:hover {
  box-shadow: var(--box-shadow-hover);
}

/* 表格行悬停效果 */
.el-table__row {
  transition: all 0.2s ease;
}

.el-table__row:hover {
  background-color: rgba(64, 158, 255, 0.05) !important;
}

/* 分页样式 */
.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 对话框样式 */
.dialog-shadow {
  border-radius: var(--border-radius-lg);
  box-shadow: var(--box-shadow-hover);
  overflow: hidden;
}

/* 按钮样式 */
.el-button {
  border-radius: var(--border-radius);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 10px;
  }
  
  .el-card {
    padding: 15px;
  }
  
  .el-table-column {
    min-width: auto !important;
  }
  
  .el-pagination {
    white-space: normal;
    justify-content: center;
  }
  
  .dialog-shadow {
    width: 90%;
  }
}
</style>